﻿using System;
using System.Collections.Generic;
using Cashbook.Models;
using Cashbook.Services;
using Xamarin.Forms;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace Cashbook.Views
{
    public partial class EditCustomerPage : ContentPage
    {
		public Customer Customer { get; set; }
		private CustomersDataAccess dataAccess;

		public EditCustomerPage(int customerId)
		{
			//  _db = db;
			InitializeComponent();
			this.dataAccess = new CustomersDataAccess();

            if(customerId>0){
                Customer = this.dataAccess.GetCustomerAsync(customerId).Result;
                this.Title = "编辑客户";
            }else{
                Customer = new Customer();

            }
			
			BindingContext = this;
		}

		async void OnAddClick(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(companyNameEntry.Text))
			{
				await DisplayAlert("错误", "请输入公司名称", "关闭");
				companyNameEntry.Focus();
				return;
			}
			if (!IsEmail(emailEntry.Text))
			{
				await DisplayAlert("错误", "请输入正确的邮箱", "关闭");
				emailEntry.Focus();
				return;
			}		


            await this.dataAccess.SaveCustomerAsync(Customer);
            this.dataAccess.Customers = await this.dataAccess.GetCustomersOC();

			//MessagingCenter.Send(this, "AddItem", bill);
			//await Navigation.PopToRootAsync();
            await Navigation.PushAsync(new CustomersPage());
		}


		public bool IsEmail(string email)
		{
			//if (String.IsNullOrEmpty(email))
			//{ return false; }
			try
			{
				Regex _regex = new Regex("^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])" +
						"+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)" +
						"((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|" +
						"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\u" +
						"FDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|" +
						"(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|" +
						"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900" +
						"-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFF" +
						"EF])))\\.?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
				return _regex.IsMatch(email);
			}
			catch (RegexMatchTimeoutException)
			{
				return false;
			}
		}
    }
}
